package com.vimi8.ebb.auth.utils;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by think on 2016/12/15.
 */
public class TokenConvertUtil {
    /**
     * 获取token*/
public static String obtainToken(HttpServletRequest request){
    String cookieToken=null;
    Map<String,Cookie> cookieMap = ReadCookieMap(request);
    if(cookieMap.containsKey("Authorization")){
        Cookie cookie = (Cookie)cookieMap.get("Authorization");
        String value=cookie.getValue();
        if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
            String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
            if(authHeaderValue.startsWith("%20")){
                authHeaderValue=authHeaderValue.substring(3);
            }
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE,
                    value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim());
            int commaIndex = authHeaderValue.indexOf(',');
            if (commaIndex > 0) {
                authHeaderValue = authHeaderValue.substring(0, commaIndex);
            }
            cookieToken= authHeaderValue;
        }
    }
    return cookieToken;

}

    /**
     * 根据request转换token为用户信息*/
    public static JSONObject extractCookieToken(HttpServletRequest request) {
        String cookieToken=obtainToken(request);
        JSONObject jsonObject=new JSONObject();
        if(!StringUtils.isEmpty(cookieToken)){
            try {
                Jwt jwt = JwtHelper.decode(cookieToken);
                String claims = jwt.getClaims();
                jsonObject = JSONObject.fromObject(claims);
            } catch (Exception e) {

            }
        }
        return jsonObject;
    }

    public static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
//    public static void main(String[] args){
//        String cookieToken="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiaW5kdXN0cmlhbC1wbGF0Zm9ybSIsImF1dGgtc2VydmVyIiwiZGF0YS1kaXJlY3RvcnkiLCJlYmItcGxhdGZvcm0iLCJpbmZvLXNlcnZlciJdLCJjbGllbnRPcmdDbGFzcyI6Im9yZ19jb2xsZWN0aXZlIiwidXNlcl9uYW1lIjoiMTgxNjY3MzYzNjciLCJvcGVuaWQiOiIzNmFhZDFlYi03ODc4LTQ2OTktYTE3OC05OTU1NDgxZmFjM2QiLCJzY29wZSI6WyJ1c2VyLW1lIiwidXNlciIsImFkbWluIl0sImV4cCI6MTQ4MjQxMzg4OSwiam9iIjoib3JnX2NvcnAiLCJqdGkiOiJjYmMxNWViYy00OWUyLTRiZjMtYjRiNi0zOTA0ZTM5MmMxNzgiLCJjbGllbnRfaWQiOiJlOTI1MDU2NS02YTY4LTQ1NWUtOTk2ZC00ZmVjN2M1NmQ4YzgifQ.sDk8D-o-nOACrUNtfwoasbvUpQXKNseA8yJv6tTQFOo7ps4AZESUNiLj2to9Vg_jipeM6aAG6nxuzpAOzAO7-ul-N6GdtjFNH4AiGqfuHhRe6wC1WoyTQULuCm7VGoFDrN81jveNQBJGRSzI1AWYV0OD_SIxLeHK-THC2D8a5ZHkK8DETLlGf9bua2VKzdMtNGochUWk2vlFJdZa0KNf_X9vjSKZFohBdM6mbwXftQ_4-a0me8itPwesMBaqCZ1YDZb1MI54UkB2ussJFHtgMM6KYmQQmKrU-5wf8rC4KmXI0yJGpiWLMqFq4VR9Cn1XUgP-GQwZXyyNlVmZONS6Sw";
//        if(!StringUtils.isEmpty(cookieToken)){
//            Jwt jwt = JwtHelper.decode(cookieToken);
//            String claims = jwt.getClaims();
//            JSONObject  jsonObject = JSONObject.fromObject(claims);
//            System.out.print("token convert user "+jsonObject);
//        }

       // JSONObject headerJSONObject=JSONObject.fromObject(header);
        //System.out.print("headerJSONObject "+headerJSONObject);
//    }
public static JSONObject convertToken(String token){
    JSONObject  jsonObject =new JSONObject();
    if(!StringUtils.isEmpty(token)){
            Jwt jwt = JwtHelper.decode(token);
            String claims = jwt.getClaims();
            jsonObject = JSONObject.fromObject(claims);
        }
    return jsonObject;
}
}
